package thread;

/**
 * 用三个线程按顺序打印 abc 三个字母，比如 abcabcabc
 *
 * @author yujiafan
 * @version 1.0.0
 * @create 2022-05-25
 */
public class PrintABC {

    public static class TestThread implements Runnable{

        private String str;
        private Object pre;
        private Object self;

        TestThread(String str,Object pre,Object self){
            this.str = str;
            this.pre = pre;
            this.self = self;
        }

        @Override
        public void run() {
            Integer count = 3;
            while (count > 0){
                synchronized (pre){
                    synchronized (self){
                        System.out.print(str);
                        count--;
                        self.notifyAll();
                    }
                    try {
                        pre.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    public static void main(String[] args) throws InterruptedException {
        Object o1 = new Object();
        Object o2 = new Object();
        Object o3 = new Object();
        TestThread t1 = new TestThread("a", o3, o1);
        TestThread t2 = new TestThread("b", o1, o2);
        TestThread t3 = new TestThread("c", o2, o3);
        new Thread(t1).start();
        Thread.sleep(100);
        new Thread(t2).start();
        Thread.sleep(100);
        new Thread(t3).start();
    }
}
